<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=yes">
  
  
  <title>  VueX的相关使用 |   写夜子的个人博客 </title>

 
  
    <link rel="icon" href="/images/favicon.png">
  


  <link rel="stylesheet" href="/nayo.min.css"> 
</head>  
  <body>   
    
      <header class="header">
	
  <nav class="header-nav">        
   
    <span class="iconfont icon-menu mobile-toggle"></span>   	

    <div class="header-menu">          
              
            
              <a class="header-menu-link" id="header-menu-home" href="/">首页</a>     
            
            
            
              <a class="header-menu-link" id="header-menu-archives" href="/archives">归档</a>     
            
            
            
              <a class="header-menu-link" id="header-menu-tags" href="/tags">标签</a>     
            
            
            
              <a class="header-menu-link" id="header-menu-about" href="/about">关于</a>     
            
            
            
              <a class="iconfont icon-menu-search header-menu-link" id="header-menu-search"></a>
            
                
    </div>  
    
  </nav>
</header>   

      <div class="container">       
          
          
            <section class="main">  
          

          <article class="post">
  
	<div class="post-header">

	<p class="post-title">	
		VueX的相关使用
	</p>
			

	<div class="meta-info">	
	<span>
		9月 03, 2018
	</span>

	
	
		<i class="iconfont icon-words"></i>
		<span>
			2891
		</span>
	
</div>

</div> 
	 

	  <div class="post-content slideDownMin">

		

			
					<h3 id="VueX是什么"><a href="#VueX是什么" class="headerlink" title="VueX是什么?"></a>VueX是什么?</h3><p>  Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能.<br>  <a id="more"></a><br>  总的来说,我们对一个单向的数据流的操作如下图:<br>  <img src="http://wx4.sinaimg.cn/mw690/89296167gy1fuwd8r9apvj20zk0o2gm0.jpg" alt="flow"></p>
<p>  我们在视图(view)上对数据进行了类似于点击等操作,就会通过Action触发对数据的状态(State)的改变,就形成了这样的单向数据流操作.</p>
<h3 id="为什么要用VueX？"><a href="#为什么要用VueX？" class="headerlink" title="为什么要用VueX？"></a>为什么要用VueX？</h3><p>  许多组件需要同时共享一个数据的使用和更新,但是组件之间无法全然构成子父级组件的关系,此时针对这个数据就需要一个公共的状态管理器,也就是VueX.所以当项目组件与组件之间存在着太复杂的共享关系和操作时,就应该使用VueX.</p>
<h3 id="VueX的核心"><a href="#VueX的核心" class="headerlink" title="VueX的核心"></a>VueX的核心</h3><p>  每一个 Vuex 应用的核心就是 store（仓库）.“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state).Vuex 和单纯的全局对象有以下两点不同:</p>
<ol>
<li><p>Vuex 的状态存储是响应式的.当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新.</p>
</li>
<li><p>你不能直接改变 store 中的状态.改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation.这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用.      </p>
</li>
</ol>
<p>   VueX其实就是为上图的三个操作增加了流程,如下图:<br>   <img src="http://wx2.sinaimg.cn/mw690/89296167gy1fuwdllhvgoj20jh0fbwef.jpg" alt="VueX"></p>
<p>   VueX增加了Mutation.在这里,将操作(Action)统一提交到Mutation,在Mutation经过一系列的处理,再改变(状态)State,状态改变之后,再反应到视图(view)上.<br>   就像下面这样:<br>   <img src="http://wx1.sinaimg.cn/mw690/89296167gy1fuwdzb7lvbj20q903fglk.jpg" alt="VueX流程图"><br>   所以VueX就很好理解了.就是统一管理公共状态的东西.<br>   不过需要注意一点:<br>   Action不是必需的操作,如果有异步操作时才用到Action,否则可以不使用.也就是说,View可以直接提交到Mutation,从而改变状态,引起视图的改变.<br>   Action 类似于 mutation,不同在于:</p>
<ul>
<li>Action 提交的是 mutation,而不是直接变更状态.</li>
<li>Action 可以包含任意异步操作.      </li>
</ul>
<h3 id="核心概念和使用"><a href="#核心概念和使用" class="headerlink" title="核心概念和使用"></a>核心概念和使用</h3><ol>
<li>核心概念</li>
</ol>
<ul>
<li>State</li>
<li>Getter</li>
<li>Mutation</li>
<li>Action         </li>
</ul>
<ol start="2">
<li>VueX的基本使用         </li>
</ol>
<p>  安装(npm):<br>  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install vuex --save</span><br></pre></td></tr></table></figure></p>
<p>  引入:<br>  在项目src文件夹下新建store文件夹,再到store文件夹新建index.js文件:<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> Vuex <span class="keyword">from</span> <span class="string">'vuex'</span></span><br><span class="line"></span><br><span class="line">Vue.use(Vuex)</span><br><span class="line"><span class="comment">//创建一个store仓库</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">  state:&#123;</span><br><span class="line">    count: <span class="number">11</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>  注:目前vue官方没有关于vuex的脚手架工具,所以必须手动store文件夹和index.js文件.<br>  在main.js导入:<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">'./store'</span></span><br></pre></td></tr></table></figure></p>
<p>  新建State(在index.js文件)<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">state:&#123;</span><br><span class="line">  count: <span class="number">11</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>  在外部组件中获取count的值:<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> computed:&#123;</span><br><span class="line">  getCount()&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.$store.state.count;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这里的this.$store.state.count即是通过State获取</span></span><br></pre></td></tr></table></figure></p>
<p>  不过一般都会为state添加Getter:Vuex 允许我们在 store 中定义“getter”（可以认为是 store 的计算属性）.就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算.<br>  在这里我们为count新建一个getter(在index.js):<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">getters:&#123;</span><br><span class="line">  getState(state)&#123;</span><br><span class="line">    <span class="keyword">return</span> state.count &gt; <span class="number">0</span> ? state.count : <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>  所以在组件中获取count值的方法要通过getter:<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"> computed:&#123;</span><br><span class="line">  getCount()&#123;</span><br><span class="line">    <span class="comment">// return this.$store.state.count;</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.$store.getters.getState;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这里的this.$store.getters.getState即是通过getter获取</span></span><br></pre></td></tr></table></figure></p>
<p>  状态(State)和getter建好以后,我们先通过mutations改变count的值:<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mutations:&#123;</span><br><span class="line">  incres(state)&#123;</span><br><span class="line">    state.count++;</span><br><span class="line">  &#125;,</span><br><span class="line">  decre(state)&#123;</span><br><span class="line">    state.count--;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这里的incres函数即为count作++操作,decre函数为count作--操作</span></span><br></pre></td></tr></table></figure></p>
<p>  在外部组件中使用:<br>  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">name</span>=<span class="string">"button"</span> @<span class="attr">click</span>=<span class="string">"add"</span>&gt;</span>加加<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 这里为template里面的内容 --&gt;</span></span><br></pre></td></tr></table></figure></p>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">methods:&#123;</span><br><span class="line">  add()&#123;</span><br><span class="line">    <span class="keyword">this</span>.$store.commit(<span class="string">"incres"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//在这里通过commit调用了incres函数</span></span><br></pre></td></tr></table></figure>
<p>  以上就是通过mutations改变count的值,接下来我们通过actions来改变count的值:<br>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">actions: &#123;</span><br><span class="line">  <span class="comment">// context 承上启下,在这里可以通过context调用到commit的执行</span></span><br><span class="line">  incres(context)&#123;</span><br><span class="line">    context.commit(<span class="string">"incres"</span>);</span><br><span class="line">  &#125;,</span><br><span class="line">  decre(context)&#123;</span><br><span class="line">    context.commit(<span class="string">"decre"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>  在外部组件中使用:<br>  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">name</span>=<span class="string">"button"</span> @<span class="attr">click</span>=<span class="string">"min"</span>&gt;</span>减减<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 这里为template里面的内容 --&gt;</span></span><br></pre></td></tr></table></figure></p>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">methods:&#123;</span><br><span class="line">  min()&#123;</span><br><span class="line">    <span class="keyword">this</span>.$store.dispatch(<span class="string">"decre"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//在这里通过dispatch调用了decre函数</span></span><br></pre></td></tr></table></figure>
<p>  以上就是通过actions改变count的值.<br>  总结:mutation 像事件注册,需要相应的触发条件.而 Action 就是那个管理触发条件的.mutations只能同步执行,actions则可以执行异步操作.</p>
  	
					
	  </div>     
	  

	
<div class="post-meta">
      	

      
        <i class="iconfont icon-tag"></i>     
          <a class="tag-link" href="/tags/JS/">JS</a> <a class="tag-link" href="/tags/Vue/">Vue</a>    
      	
</div>





<div class="post-footer">
  <div class="pf-left">
      <img class="pf-avatar" src="http://wx2.sinaimg.cn/mw690/89296167gy1fu5ph67x17j21kw1kwhdu.jpg">
      <p class="pf-des">hi,我是写夜子,希望你有愉快的一天.</p>
  </div>

  <div class="pf-right">           
      <div class="pf-links">
        




<span class="donate-btn">
	<span class="iconfont icon-donate"></span>
</span>


<div id="donate-box" class="sildeUpMin">

	<span class="donate-cancel iconfont icon-cancel"></span>

	<div class="donate-img-box">
		<img id="donate-qr-wechat" class="noLazyLoad donate-img" src="/images/donate1.png" alt="No Donate Image!">	
		<img id="donate-qr-alipay" class="noLazyLoad donate-img lazyload" src="/images/placeholder.png" alt="No Donate Image!" data-src="/images/donate2.png">	
	</div>

	<span class="donate-word">世界美好 你也是</span>

	<div class="donate-list">
		<span class="iconfont icon-donate-wechat"></span>
		<span class="iconfont icon-donate-alipay"></span>
	</div>

</div>

 
        
	
<script id="-mob-share" src="http://f1.webshare.mob.com/code/mob-share.js?appkey=21d601593a1de"></script>
	
	<span class="share-btn">
	<span class="iconfont icon-share"></span>
	</span>


	<div class="-mob-share sildeUpMin">
		   			             
            <a class="iconfont  icon-share-qq -mob-share-qq"></a>		
     	   			             
            <a class="iconfont  icon-share-weixin -mob-share-weixin"></a>		
     	   			             
            <a class="iconfont  icon-share-weibo -mob-share-weibo"></a>		
     	   			             
            <a class="iconfont  icon-share-douban -mob-share-douban"></a>		
     	   			             
            <a class="iconfont  icon-share-facebook -mob-share-facebook"></a>		
     	   			             
            <a class="iconfont  icon-share-twitter -mob-share-twitter"></a>		
     	   			             
            <a class="iconfont  icon-share-google -mob-share-google"></a>		
     	   
	</div>	

      </div>  
    <nav class="pf-paginator">
      
         
          <a href="/2018/09/24/Gulp的基本使用/" data-hover="gulp的基本使用">上一篇</a>      
            
        
      
        
        <a href="/2018/09/02/Vue路由的基本加载/" data-hover="路由的基本加载"> 下一篇</a>
            
  </nav>   
  </div>
</div> 
	
	
</article>

          </section> 
      </div>            
    
    <a id="backTop">
      <span>
        <i class="iconfont icon-backtotop"></i>
      </span>
    </a> 

  
    
    <div class="search-container sildeUpMin">
        <div class="search-header">
            <input type="text" placeholder="输入你想搜索的" id="search-input" class="search-input">  
            <span class="search-cancel iconfont icon-cancel"></span>
        </div>
        <div id="search-result" class="search-result"></div>
    </div>
 
     <div class="mobile-menu">      

      
      <img class="mobile-menu-icon lazyload" src="/images/placeholder.png" data-src="/images/favicon.png">   
      

         
            

            <a class="mobile-menu-link" href="/">首页
            </a>
            
         
            

            <a class="mobile-menu-link" href="/archives">归档
            </a>
            
         
            

            <a class="mobile-menu-link" href="/tags">标签
            </a>
            
         
            

            <a class="mobile-menu-link" href="/about">关于
            </a>
            
         
                          

            <a class="mobile-menu-link mobile-menu-search" href="#">搜索 </a>                 
            
         
      
</div>        
    


<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?636802045446222199ae541e32c8133e"; 
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>





     
    




<footer id="footer">


		<div class="footer-copyright">
		&copy;
		
		2018-
		
		2020

		Xieyezi
		<br>

		Copyright
		<a href="https://github.com/xieyezi" target="_blank">Xieyezi</a>
		</div>

</footer>
   

  

    <script src="/nayo.bundle.js"></script>           
  </body>        
</html>